package com.jzo2o.market.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.request.CouponOperationPageQueryReqDTO;
import com.jzo2o.market.model.dto.response.CouponInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponUseBackService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Resource(name = "seizeCouponScript")
    private DefaultRedisScript<String> seizeCouponScript;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponUseBackService couponUseBackService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;

    @Resource
    private CouponMapper couponMapper;


    @Override
    public PageResult<CouponInfoResDTO> pagequery(CouponOperationPageQueryReqDTO couponOperationPageQueryReqDTO) {
        LambdaQueryWrapper<Coupon> wrapper = Wrappers.<Coupon>lambdaQuery()
                .eq(couponOperationPageQueryReqDTO.getActivityId() != null, Coupon::getActivityId, couponOperationPageQueryReqDTO.getActivityId())
                .orderByDesc(Coupon::getCreateTime);
        Page<Coupon> couponPage = PageUtils.parsePageQuery(couponOperationPageQueryReqDTO, Coupon.class);
        Page<Coupon> couponPage1 = couponMapper.selectPage(couponPage, wrapper);
        PageResult<CouponInfoResDTO> pageResult = PageUtils.toPage(couponPage1, CouponInfoResDTO.class);
        return pageResult;
    }

    @Override
    public List<CouponInfoResDTO> myCouponList(Integer status, Integer lastid) {
        Long l = UserContext.currentUserId();
        List<Coupon> list = this.lambdaQuery().eq(Coupon::getUserId, l).eq(Coupon::getStatus, status).orderByDesc(Coupon::getCreateTime).list();
        List<CouponInfoResDTO> couponInfoResDTOS = BeanUtil.copyToList(list, CouponInfoResDTO.class);
        return couponInfoResDTOS;
    }
}
